/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src;

/**
 *
 * @author jasuke
 *
 * add modified by chan
 */

import com.sun.faces.taglib.html_basic.OutputTextTag;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UICommand;
import javax.faces.component.html.HtmlOutputText;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.component.tabview.Tab;
import org.primefaces.component.tabview.TabView;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.event.TabChangeEvent;
import org.primefaces.event.TabCloseEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import src.domain.security.Policy;
import src.domain.security.Ugpolicy;
import src.services.security.UgpolicyModel;
import src.util.Constanta;

@ManagedBean
@SessionScoped
public class MenuBean implements Serializable{

    private TreeNode root;
    private List<Menu> menuTabs;
    private List<Menu> menuAll;
    private List<Object[]> menuAccess;
    private List<Menu> showTabs;
    private List<Module> listModule;    
    private TabView tabView;
    private Tab selectedTab;
    private int tabCount;
    private TreeNode selectedNode;
    private int tabActiveIndex;
    private Menu selectedMenu;
    
    

    

  //  private MenuModel model;

    public MenuBean() {
        menuTabs = new ArrayList<>();      
        root = new DefaultTreeNode("Root", null);      
        tabActiveIndex = -1;
        tabView = new TabView();
        listModule = new ArrayList<>();


        List<Menu> ls  = new ArrayList<> ();

        FacesContext fc = FacesContext.getCurrentInstance();
        //Session session = (Session) fc.getExternalContext().getSession(false);
        HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
        //session.getAttribute("ipAdress");
        
        
        src.services.MenuModel menuModel = new src.services.MenuModel();
        Map<String, Object> filters = new HashMap<>();
        filters.put("menu.hide = ", 0);
        filters.put("menu.disabled = ", 0);
        //filters.put("policy.ugroup.ugroupId= ", 1);
        if (session!=null)
            filters.put("policy.ugroup.ugroupId= ", session.getAttribute("groupid"));
            
        else
            filters.put("policy.ugroup.ugroupId= ", null);
        /*
         * from Ugpolicy as policy, Menu as menu 
where policy.id.menuId=100 and menu.menuId = policy.id.menuId and policy.ugroup.ugroupId = 1

         */
        //menuAll = menuModel.findAll(filters);
        menuAccess = menuModel.findSecurity(filters);
        Module m = new Module();
        m.setModulName("");
        TreeNode parent = null;
        TreeNode parent2 = null;        
       
        /*menu = (Menu) obj[0]
        ugpoly = obj[1]));
       }
       * 
       */
        
    /*    for (Object[] obj:menuAccess){
            Menu menu = (Menu)obj[0];
            Ugpolicy policy = (Ugpolicy)obj[1];
        }
        * 
        */
        
     /*   for (int i=0;i<menuAll.size();i++){
           Menu menu = menuAll.get(i); 
           * 
           */
        int i=0;
        UgpolicyModel helperUg = new UgpolicyModel();
        String modulName = "";
        for (Object[] obj:menuAccess){
            Menu menu = (Menu)obj[0];
            Ugpolicy policy = (Ugpolicy)obj[1];
            
            if (menu.getMenuType().equals("ROOT")){
                i++;
                continue;
            }
           // if (parent==null)
                 //xx = new DefaultTreeNode(menu, rootNode);
            //else
                //xx = new DefaultTreeNode(menu, parent);
            
            //if (menu.getMenuType().equals("ROOT")){
            if (modulName.equals("")){
                modulName = menu.getMenuGroup();
                m.setModulName(StringUtils.capitalize(modulName.toLowerCase().replace('_', ' ')));
            }
            
            if (!modulName.equals(menu.getMenuGroup())){
                modulName = menu.getMenuGroup();
                
                    
                    listModule.add(m);    
                     m = new Module();
                     m.setModulName(StringUtils.capitalize(menu.getMenuGroup().toLowerCase().replace('_', ' ')));
                
          //          rootNode.getChildren().add(parent2);
                
                
                parent = null;
                //i++;
              
                //continue;
            }
           // if (!m.getModulName().equals(menu.getMenuGroup())){
               
              //  m = new Module();
              //  m.setModulName(menu.getMenuGroup());
           // }
          //  else {
                
                if (menu.getMenuType().equals("SUBMENU")){
                    m.addMenuList(menu ,parent);
                    parent = m.getTreeNodeFromId(menu.getMenuId(),parent);
                  //  parent2.getChildren().add(parent);
                }
                else{
                    if (menu.getMenuType().equals("SETTING")) {
            //             rootNode.getChildren().add(parent);
                        parent = null;
                    }
                    
                    if (policy.getAllowedActions()!= null){
                        if (!policy.getAllowedActions().equals("")){
                            src.domain.security.Policy gpolicy = new Policy();
                            gpolicy.setCanAdd(policy.getAllowedActions().indexOf(Constanta.POLICY_INSERT)>-1);
                            gpolicy.setCanApprove(policy.getAllowedActions().indexOf(Constanta.POLICY_APPROVAL)>-1);
                            gpolicy.setCanDelete(policy.getAllowedActions().indexOf(Constanta.POLICY_DELETE)>-1);
                            gpolicy.setCanEdit(policy.getAllowedActions().indexOf(Constanta.POLICY_UPDATE)>-1);
                            gpolicy.setCanOpen(policy.getAllowedActions().indexOf(Constanta.POLICY_OPEN)>-1);
                            gpolicy.setCanPrint(policy.getAllowedActions().indexOf(Constanta.POLICY_PRINT)>-1);
                            
                            menu.setGroupPolicyAction(gpolicy);
                            m.addMenuList(menu ,parent);
                        }    
                    }
                    
                }
                
                 /*if (parent==null){
                    TreeNode xx = new DefaultTreeNode(menu, rootNode);
                 }
                 else{
                    TreeNode xxx = new DefaultTreeNode(menu, parent);
                 }
                 * 
                 */
                
                parent2 = parent;
                
                //if (i==menuAll.size()-1){
                if (i==menuAccess.size()-1){
                    listModule.add(m);
              //      rootNode.getChildren().add(parent);
                } 
            i++;
        }
        //recalculate module
        
        for (i=listModule.size()-1;i>=0;i--){
            //removeFromListModule(listModule.get(i));
           // if (listModule.get(i).getRootNode().getChildCount()>0){
             //   listModuleSecurity.add(listModule.get(i));
            //}
            if (((listModule.get(i).getRootNode().getData().equals("root"))||(listModule.get(i).getRootNode().getData() instanceof Menu ))&&
                    (listModule.get(i).getRootNode().getChildCount()==0)){
                listModule.get(i).setRootNode(null);
            }
            else {
                for ( int j=listModule.get(i).getRootNode().getChildCount()-1;j>=0;j--){
                    TreeNode node = listModule.get(i).getRootNode().getChildren().get(j);
                    Menu  menu = listModule.get(i).getMenuList().get(j);
                    if ((node.getChildCount()==0)&&((menu.getMenuType().equals("SUBMENU")||(menu.getMenuType().equals("ROOT"))))){
                        listModule.get(i).getRootNode().getChildren().remove(j);//   set(j,null);
                    }
                    else if ((node.getChildCount()>0)){
                        for ( int x=node.getChildCount()-1;x>=0;x--){
                            TreeNode node2 = node.getChildren().get(x);
                            Menu menu2 = (Menu) node2.getData();
                            if ((node2.getChildCount()==0)&&((menu2.getMenuType().equals("SUBMENU")||(menu2.getMenuType().equals("ROOT"))))){
                                listModule.get(i).getRootNode().getChildren().get(j).getChildren().remove(x);//   set(j,null);
                            }
                        }
                        node = listModule.get(i).getRootNode().getChildren().get(j);
                        if ((node.getChildCount()==0)&&((menu.getMenuType().equals("SUBMENU")||(menu.getMenuType().equals("ROOT"))))){
                            listModule.get(i).getRootNode().getChildren().remove(j);//   set(j,null);
                        }
                    }
                }
            }
            
            if (listModule.get(i).getRootNode()==null) {
                listModule.remove(i);
                continue;
            }
            if (listModule.get(i).getRootNode().getChildCount()==0){
                listModule.remove(i);
                
            }
          //  removeNodeSecurity(listModule.get(i).getRootNode());
        }
        
        showTabs = new ArrayList<>();
      //tambahkan menu baru disini......
              Menu about = new Menu();
              about.setMenuId(-1);
              about.setMenuName("About");
              about.setMenuNameEn("About");
              about.setUrl("about.xhtml");
              showTabs.add(about);
              tabActiveIndex = showTabs.size()-1;

            //  tabCount = 0;
               Tab tab = new Tab();
                 tab.setClosable(true);
                 tab.setTitle("About"+tabCount);
                 OutputTextTag txt = new OutputTextTag();
                 txt.setTitle(null);
                 UICommand z = new UICommand();
                 z.setValue("tes "+tabCount);
                // IncludeHandler include = new IncludeHandler();
                 tab.getChildren().add(z);
                tabView.getChildren().add(tab);

   }

    public void setTabCount(int tabCount) {
        this.tabCount = tabCount;
    }
   
    public int getTabActiveIndex() {
        return tabActiveIndex;
    }

    public void setTabActiveIndex(int tabActiveIndex) {
        this.tabActiveIndex = tabActiveIndex;
    }

    public int getTabCount() {
       // this.tabCount = this.tabView.getChildCount();
       // this.tabCount++;
        return this.tabCount;
    }

    public TreeNode getRoot() {
        return root;
    }

     public List<Menu> getMenuTabs() {
        return menuTabs;
    }

    public List<Menu> getShowTabs() {
        return showTabs;
    }

    public TabView getTabView() {
        return tabView;
    }

    public void setTabView(TabView tabView) {
        this.tabView = tabView;
    }

    public List<Module> getListModule() {
        return listModule;
    }

    public void setListModule(List<Module> listModule) {
        this.listModule = listModule;
    }


    public void increment(){
        FacesContext fc = FacesContext.getCurrentInstance();
        int val =2;
        String x = fc.getExternalContext().getRequestParameterMap().get("val");
        if (x!=null)
            val = Integer.parseInt(fc.getExternalContext().getRequestParameterMap().get("val"));

        this.tabCount+=val;
        Tab tab = new Tab();
         tab.setTitle("Title: "+tabCount);
//        tab.setId("tab"+tabCount);

         showTabs.add(new Menu());
       //tabView.getChildren().add(tab);

    }

    public TreeNode getSelectedNode() {
        return selectedNode;
    }

    public void setSelectedNode(TreeNode selectedNode) {
        this.selectedNode = selectedNode;
    }

    public void onNodeSelect(NodeSelectEvent event) {
        // FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Selected", event.getTreeNode().getData().toString());
        //  increment();
        //FacesContext.getCurrentInstance().addMessage(null, msg);
        /*
         * 
         */
         if (event.getTreeNode().getChildCount() == 0) {
                Menu x = (Menu)event.getTreeNode().getData();
                if ((!this.isExistMenuOnTabs(x.getMenuId()))&&((x.getUrl()!=null)||(!x.getUrl().equals("")))){
                    // ini model kalo pake menuAll  showTabs.add(menuAll.get(menuAll.indexOf(x)));
                    this.selectedMenu = x;
                    showTabs.add(x);
                    tabActiveIndex = showTabs.size()-1;
                }
                else {
                    //show underconstrutction message
                    
                    //FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Info", "UnderConstruction") );  
                    // context.addCallbackParam("success", true);  
                }
         } else {
            // Expand or Contract the Tree Node.
            if (event.getTreeNode().isExpanded())
                event.getTreeNode().setExpanded(false);
            else 
                event.getTreeNode().setExpanded(true);
        }      

    }

    public void onTabChange(TabChangeEvent event) {  
    //    FacesMessage msg = new FacesMessage("Tab Changed", "Active Tab: " + event.getTab().getTitle());  
       /* int idx = Integer.parseInt( event.getTab().getId().replaceAll("tab", ""));
        Menu x = showTabs.get(idx-1);
        if (x!=null){
           this.selectedMenu = x;     
      //     tabActiveIndex = idx-1;
        }
  */
      //  FacesContext.getCurrentInstance().addMessage(null, msg);  
    }
    
    public Menu getSelectedMenu() {
        return selectedMenu;
    }

    
   private HtmlOutputText createString( String text){
      HtmlOutputText temp = new HtmlOutputText();
      temp.setTitle(text);
      return temp;
   }



    public void addTab(){
       // menuTabs.add(new Menu("jenisAnggota","Jenis Anggota","master/jenis_anggota.xhtml"));

       // menuTabs.add(new Menu(title, url));
       //tabView.getChildren().add(0, newTab);
        // Tab tab = new Tab();
        // tab.setTitle("Title: "+title);
         //tab.setId(tabId);

         //tabView.getChildren().add(tab);
        //return ;
          /*FacesContext  fc = FacesContext.getCurrentInstance();
	  Map<String,String> params = fc.getExternalContext().getRequestParameterMap();
	*/
       // showTabs.add(new Menu(title, title, url));
         // showTabs.add(new Menu("About","Aboutt GELO","coba.xhtml"));
      //    menuTabs.add(new Menu("jenisAnggota","Jenis Anggota","master/anggota.xhtml"));
              //  this.tabCount++;
        //showTabs.add(new Menu(params.get("title"),params.get("title"),params.get("url")));
        //showTabs.add(new Menu(params.get("tttt"),params.get("tttt"),params.get("url")));

         FacesContext fc = FacesContext.getCurrentInstance();
        String title = fc.getExternalContext().getRequestParameterMap().get("title");
        Integer id = Integer.parseInt(fc.getExternalContext().getRequestParameterMap().get("id"));
        String url = fc.getExternalContext().getRequestParameterMap().get("url");
        //this.tabCount+=val;
           Menu about = new Menu();
              about.setMenuId(id);
              about.setMenuName(title);
              about.setMenuNameEn(title);
              about.setUrl(url);
              
        Tab tab = new Tab();
         tab.setTitle("Title: "+tabCount);
         
//        tab.setId("tab"+tabCount);
         if (!this.isExistMenuOnTabs(id)){
             showTabs.add(about);//menuAll.get(menuAll.indexOf(id)));
             tabActiveIndex = showTabs.size()-1;
         }


    }

    private boolean isExistMenuOnTabs(Integer id){
          // Search for element in list
        boolean found = false;
       for (int i=0;i<showTabs.size();i++)   {
           Menu m = showTabs.get(i);
           if (m.getMenuId().equals(id)) {
               found = true;
               tabActiveIndex = i;
               break;
           }
       }
        return found;
    }

    public void onChange(TabChangeEvent event){
        Tab tab =  event.getTab();
        //tab.c
    }
    
     public void onTabClose(TabCloseEvent event){
        Tab tab =  event.getTab();
        if (tab != null) {
            int idx = Integer.parseInt(tab.getId().replaceAll("tab", ""));
            Menu menu = showTabs.get(idx-1);
            /*for (Object[] obj:menuAccess){
            Menu menu = (Menu)obj[0];
            Ugpolicy policy = (Ugpolicy)obj[1];
            */
        //showTabs.re
          
            //Menu menu = (Menu)menuAccess.get(menuAccess)[0];
            if (menu !=null){
                if (menu.getBeanname()!=null){
                    FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove(menu.getBeanname());
                }
                /*switch (menu.getMenuId()){
                    case 301 :
                       FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("loanBean");
                        break;
                }
                * 
                */
            }
           
            //if ((tab.getTitletip()!=null)
                if ((tab.getTitletip()!=null)&&(!tab.getTitletip().equals("")) ){
                    //FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove(tab.getTitletip());
                   // FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("#{SavdepoBean}");
                 //   Bean bean = (Bean) request.getSession().getAttribute("beanName");
                 //    FacesContext context = FacesContext.getCurrentInstance();  
                //    Application app = context.getApplication();  
                    ///ValueExpression expr = app.getExpressionFactory().;// createBehavior("#{SavdepoBean}")
                    //ValueBinding binding = app.createValueBinding("#{" + expr + "}");  
                    //Object value = expr.getValue(context); 
                    //FacesContext context = FacesContext.getCurrentInstance(); 
                    //context.getExternalContext().get remove("SavdepoBean");
                }
            //}
            //
            showTabs.remove(idx-1);
        }
    }

    public void onClose(TabCloseEvent event){
        Tab tab =  event.getTab();
        if (tab != null) {
            int idx = Integer.parseInt(tab.getId().replaceAll("tab", ""));
           
        //showTabs.re
            Menu menu = menuAll.get(menuAll.indexOf(idx));
            if (menu !=null){
                switch (menu.getMenuId()){
                    case 301 :
                       FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("#{loanBean}");
                        break;
                }
            }
           
            //if ((tab.getTitletip()!=null)
                if ((tab.getTitletip()!=null)&&(!tab.getTitletip().equals("")) ){
                    //FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove(tab.getTitletip());
                   // FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("#{SavdepoBean}");
                 //   Bean bean = (Bean) request.getSession().getAttribute("beanName");
                 //    FacesContext context = FacesContext.getCurrentInstance();  
                //    Application app = context.getApplication();  
                    ///ValueExpression expr = app.getExpressionFactory().;// createBehavior("#{SavdepoBean}")
                    //ValueBinding binding = app.createValueBinding("#{" + expr + "}");  
                    //Object value = expr.getValue(context); 
                    //FacesContext context = FacesContext.getCurrentInstance(); 
                    //context.getExternalContext().get remove("SavdepoBean");
                }
            //}
            //
            showTabs.remove(idx-1);
        }
    }

    public void onShow(TabChangeEvent event){
        Tab tab =  event.getTab();
    }


 //   public void onNodeSelect(NodeSelectEvent event) {
//	String node = event.getTreeNode().getData().toString();
	//logger.info("Selected:" + node);
//}

    public List<Menu> getMenuByType(Map<String,Object> filters){
        src.services.MenuModel menuModel = new src.services.MenuModel();
        
        
        List<Menu> rs = menuModel.findAll(filters);
        return rs;
    }
    
    public boolean cekButtonAccess(Integer menuId,String buttonType){
        boolean rs=false;
        for (Object[] obj:menuAccess){
            Menu menu = (Menu)obj[0];
            Ugpolicy policy = (Ugpolicy)obj[1];
            
            if (menu.getMenuId().equals(menuId)){
                rs = (policy.getAllowedActions().indexOf(buttonType)>-1);
            }
        }
        return rs;
    }
}
